package com.education.wisdom.controller;

import com.education.common.utils.ApiReturnObject;
import com.education.common.utils.LogUtil;
import com.education.common.utils.UUIDUtils;
import com.education.wisdom.pojo.*;
import com.education.wisdom.service.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

import static com.education.common.core.BaseController.writeJSON;


/**
 * 教你赚资源目录体系 信息操作处理
 *
 * @author ruoyi
 * @date 2019-06-10
 */
@Controller
@ResponseBody
@CrossOrigin
@Slf4j
@Api(tags = {"教你赚资源目录体系接口"})
@RequestMapping("/web/catalogEarning")
public class FullCatalogEarningController {

    @Autowired
    private ICatalogEarningService catalogEarningService;

    @Autowired
    private IHelpService helpService;

    @Autowired
    private IHelpResourcesService helpResourcesService;

    @Autowired
    private IUserResourcesCopyService userResourcesCopyService;

    @Autowired
    private IResourcesPayService resourcesPayService;

    @Autowired
    private IUserAccountService userAccountService;

    @Autowired
    private ISysAppLoginService loginService;

    @Autowired
    private ICurrencyRecordService currencyRecordService;

    @Autowired
    private ICatalogService catalogService;

    @Autowired
    private JrUserCatalogBuyService userCatalogBuyService;


    /**
     * 专业课程我的购买
     */
    @GetMapping("/buyCatalog")
    public void buyCatalog(Integer userID, Integer pageNum, Integer pageSize) throws IOException {
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        if (pageNum != null && pageSize != null) {
            PageHelper.startPage(pageNum, pageSize);
        }
        List<Catalog> catalogs = catalogService.buyCatalog(userID);
        PageInfo<Catalog> info = new PageInfo<>(catalogs);
        writeJSON(info, response, "200", "success");
    }

    /**
     * 查询目录列表
     *
     * @param response
     * @throws IOException
     */
    @GetMapping("/list")
    public void list(HttpServletResponse response) throws IOException {
        log.info(LogUtil.LogInfo("查询目录列表", new Date()));
        List<CatalogEarning> catalogEarnings = catalogEarningService.selectByParentId(0);
        for (CatalogEarning catalogEarning : catalogEarnings) {
            List<CatalogEarning> earnings = catalogEarningService.selectByParentId(catalogEarning.getCatalogId());
            catalogEarning.setCatalogEarnings(earnings);
        }
        writeJSON(catalogEarnings, response, "200", "success");
    }

    @GetMapping("/separate")
    public void separate(HttpServletResponse response, Integer catalogId) throws IOException {
        log.info(LogUtil.LogInfo("查询目录列表", new Date()));
        if (catalogId == null) {
            writeJSON(catalogEarningService.selectByParentId(0), response, "200", "success");
        } else {
            writeJSON(catalogEarningService.selectByParentId(catalogId), response, "200", "success");
        }
    }

    @GetMapping("level")
    public void level(HttpServletResponse response) throws IOException {
        log.info(LogUtil.LogInfo("查询2级目录列表", new Date()));
        List<CatalogEarning> earnings = catalogEarningService.selectByParentId(0);
        List<CatalogEarning> list = new ArrayList<>();
        for (CatalogEarning catalogEarning : earnings) {
            List<CatalogEarning> earnings1 = catalogEarningService.selectByParentId(catalogEarning.getCatalogId());
            list.addAll(earnings1);
        }
        writeJSON(list, response, "200", "success");
    }

    @GetMapping("/rewardList")
    public void rewardList(HttpServletResponse response, Integer count) throws IOException {
        log.info(LogUtil.LogInfo("悬赏任务大厅", new Date()));
        List<Help> helps = helpService.selectByNotAdopted();
        if (count > helps.size()) {
            writeJSON(helps, response, "200", "success");
        } else {
            helps = helps.subList(0, count);
            writeJSON(helps, response, "200", "success");
        }
    }

    @GetMapping("/rewardListMore")
    public void rewardListMore(HttpServletResponse response, Integer pageSize, Integer pageNum) throws IOException {
        log.info(LogUtil.LogInfo("悬赏任务大厅更多接口", new Date()));
        PageHelper.startPage(pageNum, pageSize);
        List<Help> helps = helpService.selectByNotAdopted();
        for (Help help : helps) {
            SysAppLogin appLogin = loginService.selectSysAppLoginById(help.getUserId());
            help.setName(appLogin.getUserAccount());
            List<HelpResources> helpResources = helpResourcesService.selectHelpResourcesByHelpId(help.getId());
            help.setPartakeNum(helpResources.size());
        }
        writeJSON(new PageInfo<>(helps), response, "200", "success");
    }

    @GetMapping("/newResources")
    public void newResources(HttpServletResponse response, Integer count) throws IOException {
        log.info(LogUtil.LogInfo("上新资源", new Date()));
        List<UserResourcesCopy> userResourcesCopies = userResourcesCopyService.selectByNewTime(count);
        writeJSON(userResourcesCopies, response, "200", "success");
    }

    @GetMapping("/newResourcesList")
    public void newResourcesList(HttpServletResponse response, Integer pageSize, Integer pageNum) throws IOException {
        log.info(LogUtil.LogInfo("上新资源列表", new Date()));
        PageHelper.startPage(pageNum, pageSize);
        List<UserResourcesCopy> userResourcesCopies = userResourcesCopyService.selectByCatalogId(null);
        writeJSON(new PageInfo<>(userResourcesCopies), response, "200", "success");
    }

    @GetMapping("/seeDetails")
    public void seeDetails(HttpServletResponse response, Integer id) throws IOException {
        log.info(LogUtil.LogInfo("查看上新详情", new Date()));
        UserResourcesCopy userResourcesCopy = userResourcesCopyService.selectUserResourcesCopyById(id);
        writeJSON(userResourcesCopy, response, "200", "success");
    }

    @GetMapping("/queryDirectoryResources")
    public void queryDirectoryResources(HttpServletResponse response, String userId, Integer catalogId, Integer pageSize, Integer pageNum) throws IOException {
        log.info(LogUtil.LogInfo("查看目录下资源", new Date()));
        PageHelper.startPage(pageNum, pageSize);
        List<UserResourcesCopy> list = userResourcesCopyService.selectByCatalogId(catalogId);
        for (UserResourcesCopy userResourcesCopy : list) {
            if (userResourcesCopy.getIsFree().equals("2")) {
                if (userId != null) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("userId", userId);
                    map.put("resourcesId", userResourcesCopy.getId());
                    ResourcesPay resourcesPay = resourcesPayService.selectResourcesPayByMap(map);
                    if (resourcesPay != null) {
                        userResourcesCopy.setIsFree("1");
                    }
                }
            }
            SysAppLogin appLogin = loginService.selectSysAppLoginById(userResourcesCopy.getUserId());
            userResourcesCopy.setUserName(appLogin.getUserAccount());
        }
        writeJSON(new PageInfo<>(list), response, "200", "success");
    }

    @GetMapping("/checkYourself")
    public void checkYourself(HttpServletResponse response, String userId, Integer pageSize, Integer pageNum) throws IOException {
        log.info(LogUtil.LogInfo("查询自己上传资源", new Date()));
        PageHelper.startPage(pageNum, pageSize);
        List<UserResourcesCopy> list = userResourcesCopyService.selectByUserId(userId);
        writeJSON(new PageInfo<>(list), response, "200", "success");
    }

    @PostMapping("/resourceDeduction")
    @Transactional
    public void resourceDeduction(HttpServletResponse response, String userId, Integer id) throws IOException {
        log.info(LogUtil.LogInfo("购买付费资源url", new Date()));
        UserAccount userAccount = userAccountService.selectUserAccountByUserId(userId);
        UserResourcesCopy userResourcesCopy = userResourcesCopyService.selectUserResourcesCopyById(id);
        ResourcesPay pay = new ResourcesPay();
        pay.setJrUserId(userId);
        pay.setJrResourcesId(id + "");
        List<ResourcesPay> list = resourcesPayService.selectResourcesPayList(pay);
        if (list != null && list.size() > 0) {
            writeJSON("已购买", response, "201", "success");
        } else {
            if (userAccount.getCurrency() > userResourcesCopy.getCurrency()) {
                //减钱
                userAccount.setCurrency(userAccount.getCurrency() - userResourcesCopy.getCurrency());
                userAccountService.updateUserAccount(userAccount);
                //给资源拥有者加钱
                UserAccount account = userAccountService.selectUserAccountByUserId(userResourcesCopy.getUserId());
                account.setCurrency(userAccount.getCurrency() + userResourcesCopy.getCurrency());
                userAccountService.updateUserAccount(account);
                //持久化资源
                ResourcesPay resourcesPay = new ResourcesPay();
                resourcesPay.setJrUserId(userAccount.getUserId());
                resourcesPay.setJrResourcesId(userResourcesCopy.getId().toString());
                resourcesPay.setCreateTime(new Date());
                resourcesPayService.insertResourcesPay(resourcesPay);
                //添加付费记录
                CurrencyRecord currencyRecord = new CurrencyRecord();
                currencyRecord.setCurrencyId(UUIDUtils.getByUUId());
                currencyRecord.setCreateTime(new Date());
                currencyRecord.setUserId(userId);
                currencyRecord.setCurrency(new BigDecimal(userResourcesCopy.getCurrency()));
                currencyRecord.setTrxType("3");
                currencyRecordService.insertCurrencyRecord(currencyRecord);
                writeJSON(userResourcesCopy.getUrl(), response, "200", "success");
            } else {
                writeJSON("余额不足请充值", response, "201", "success");
            }
        }

    }

    @PostMapping("/rewardTask")
    public void s(HttpServletResponse response, Help help) throws IOException {
        log.info(LogUtil.LogInfo("发布悬赏任务", new Date()));
        if (help.getTitle() != null && help.getDescribes() != null && help.getUserId() != null) {
            String userId = help.getUserId();
            UserAccount account = userAccountService.selectUserAccountByUserId(userId);
            if (account.getCurrency() > help.getCurrency()) {
                account.setCurrency(account.getCurrency() - help.getCurrency());
                userAccountService.updateUserAccount(account);

                help.setCreateTime(new Date());
                help.setHelpId(UUIDUtils.getByUUId());
                help.setType("2");
                help.setBrowseNum(0);
                help.setPartakeNum(0);
                helpService.insertHelp(help);
                //添加付费记录
                CurrencyRecord currencyRecord = new CurrencyRecord();
                currencyRecord.setCurrencyId(UUIDUtils.getByUUId());
                currencyRecord.setCreateTime(new Date());
                currencyRecord.setUserId(userId);
                currencyRecord.setCurrency(new BigDecimal(help.getCurrency()));
                currencyRecord.setTrxType("6");
                currencyRecordService.insertCurrencyRecord(currencyRecord);
                writeJSON("发布成功", response, "200", "success");
            } else {
                writeJSON("达人币不足，发布失败", response, "201", "success");
            }
        }
    }

    @PostMapping("/directoryUploadResource")
    public void directoryUploadResource(HttpServletResponse response, UserResourcesCopy userResourcesCopy) throws IOException {
        log.info(LogUtil.LogInfo("目录下上传资源", new Date()));
        if (userResourcesCopy.getCatalogId() != null && userResourcesCopy.getUrl() != null) {
            userResourcesCopy.setResourcesId(UUIDUtils.getByUUId());
            userResourcesCopy.setCreateTime(new Date());
            userResourcesCopy.setIsTure("2");
            userResourcesCopyService.insertUserResourcesCopy(userResourcesCopy);
            writeJSON("上传成功", response, "200", "success");
        }
    }

    @PostMapping("/replyReward")
    public void replyReward(HttpServletResponse response, HelpResources helpResources) throws IOException {
        log.info(LogUtil.LogInfo("回复悬赏任务", new Date()));
        if (helpResources.getUrl() != null && helpResources.getUserId() != null && helpResources.getHelpId() != null) {
            helpResources.setCreateTime(new Date());
            helpResources.setIsAdopt("2");
            helpResources.setBrowse(0);
            helpResources.setIsTure("1");
            helpResources.setType("1");
            helpResources.setResourcesId(UUIDUtils.getByUUId());
            helpResourcesService.insertHelpResources(helpResources);
            writeJSON("上传成功", response, "200", "success");
        } else {
            writeJSON("资料不完善", response, "201", "success");
        }
    }

    @GetMapping("/rewardTaskDetails")
    public void rewardTaskDetails(HttpServletResponse response, Integer id) throws IOException {
        log.info(LogUtil.LogInfo("悬赏任务详情", new Date()));
        Help help = helpService.selectHelpById(id);
        SysAppLogin appLogin = loginService.selectSysAppLoginById(help.getUserId());
        help.setName(appLogin.getUserAccount());
        help.setUserIco(appLogin.getUserIco());
        List<HelpResources> helpResources = helpResourcesService.selectHelpResourcesByHelpId(help.getId());
        help.setPartakeNum(helpResources.size());
        if (help.getBrowseNum() == 0) {
            help.setBrowseNum(1);
        } else {
            help.setBrowseNum(help.getBrowseNum() + 1);
        }
        writeJSON(help, response, "200", "success");
    }

    @GetMapping("/rewardTaskDetailsList")
    public void rewardTaskDetailsList(HttpServletResponse response, Integer id, Integer pageSize, Integer pageNum) throws IOException {
        log.info(LogUtil.LogInfo("悬赏任务详情回复列表", new Date()));
        PageHelper.startPage(pageNum, pageSize);
        List<HelpResources> helpResources = helpResourcesService.selectHelpResourcesByHelpId(id);
        writeJSON(new PageInfo<>(helpResources), response, "200", "success");
    }

    @PostMapping("/adoption")
    public void adoption(HttpServletResponse response, Integer id, String userId) throws IOException {
        log.info(LogUtil.LogInfo("采纳按钮", new Date()));
        HelpResources helpResources = helpResourcesService.selectHelpResourcesById(id);
        Help help = helpService.selectHelpById(helpResources.getHelpId());
        if (help.getUserId().equals(userId)) {
            Integer count = helpResourcesService.selectByHelpIdAndIsAdopt(helpResources.getHelpId());
            if (count > 0) {
                writeJSON("问题已被采纳", response, "201", "success");
            } else {
                helpResources.setIsAdopt("1");
                helpResourcesService.updateHelpResources(helpResources);
                help.setType("1");
                helpService.updateHelp(help);
                UserAccount account = userAccountService.selectUserAccountByUserId(helpResources.getUserId());
                account.setCurrency(account.getCurrency() + help.getCurrency());
                userAccountService.updateUserAccount(account);
                //添加付费记录
                CurrencyRecord currencyRecord = new CurrencyRecord();
                currencyRecord.setCurrencyId(UUIDUtils.getByUUId());
                currencyRecord.setCreateTime(new Date());
                currencyRecord.setUserId(userId);
                currencyRecord.setCurrency(new BigDecimal(help.getCurrency()));
                currencyRecord.setTrxType("7");
                currencyRecordService.insertCurrencyRecord(currencyRecord);
                writeJSON("采纳成功", response, "200", "success");
            }
        } else {
            writeJSON("不是自己发布，采纳失败", response, "201", "success");
        }
    }

    /**
     * @param response
     * @param userId   用户ID
     * @param type     （1 已解决 2 未解决）
     */
    @GetMapping("/whetherAdoptList")
    public void whetherAdoptList(HttpServletResponse response, String userId, Integer type, Integer pageNum, Integer pageSize) throws IOException {
        log.info(LogUtil.LogInfo("是否解决列表", new Date()));
        Map<String, Object> map = new HashMap<>();
        map.put("userId", userId);
        map.put("type", type);
        PageHelper.startPage(pageNum, pageSize);
        List<Help> helps = helpService.selectByUserIdAndType(map);
        for (Help help : helps) {
            List<HelpResources> helpResources = helpResourcesService.selectHelpResourcesByHelpId(help.getId());
            help.setPartakeNum(helpResources.size());
        }
        writeJSON(new PageInfo<>(helps), response, "200", "success");
    }

    //获取父级的父级目录id以及名称
    private void getFirstCatalog(Catalog catalog) {
        Catalog catalog2 = catalogService.selectCatalogByCatalogId(catalog.getParentId());
        if (catalog2 != null) {
            Catalog catalog1 = catalogService.selectCatalogByCatalogId(catalog2.getParentId());
            if (catalog1 != null) {
                catalog.setParentCatalogId(catalog1.getCatalogId() + "");
                catalog.setParentCatalogName(catalog1.getName());
            } else {
                catalog.setParentCatalogId("");
                catalog.setParentCatalogName("");
            }
        }
    }

    /**
     * 我的购买
     *
     * @param response
     * @param userId
     * @param pageSize
     * @param pageNum
     * @throws IOException
     */
    @GetMapping("/purchaseResources")
    public void purchaseResources(HttpServletResponse response, String userId, Integer pageSize, Integer pageNum) throws IOException {
        log.info(LogUtil.LogInfo("已购买列表", new Date()));
        if (pageNum != null && pageSize != null) {
            PageHelper.startPage(pageNum, pageSize);
        }
        List<Catalog> catalogs = catalogService.selectBuyListByUserId(userId);
        for (Catalog catalog : catalogs) {
            //获取祖籍信息
            getFirstCatalog(catalog);
        }
//        List<UserResourcesCopy> list = userResourcesCopyService.selectByPay(userId);
        writeJSON(new PageInfo<>(catalogs), response, "200", "success");
    }

    /**
     * 逻辑删除我的购买
     */
    @PostMapping("/deleteById")
    public ApiReturnObject deleteById(@RequestBody JrUserCatalogBuy jrUserCatalogBuy) {
        jrUserCatalogBuy.setDeflag("0");
        int i = userCatalogBuyService.updateJrUserCatalogBuy(jrUserCatalogBuy);
        if (i > 0) {
            return new ApiReturnObject("200", "删除成功", "");
        }
        return new ApiReturnObject("201", "删除失败", "");
    }
}